package com.hua.common.http;

import android.os.Handler;
import android.os.Looper;

import com.hua.common.commontools.FileUtil;
import com.hua.common.commontools.MyLog;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by huaxiaolin on 2016/4/9.
 */
public class HttpUtil {
    public MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private Handler handler = new Handler(Looper.getMainLooper());

    private HttpUtil() {
    }

    private static class LazyHolder {
        private static final HttpUtil INSTANCE = new HttpUtil();
    }

    public static final HttpUtil getInstance() {
        return LazyHolder.INSTANCE;
    }


    public void postRequest(String url, String json,final HttpUtilCallBack httpUtilCallBack) {
        RequestBody requestBody = RequestBody.create(JSON, json);
//        HashMap headMap = new HashMap();
//        headMap.put("key", "value");
//        Headers headers = Headers.of(headMap);
        Request request = new Request.Builder()//.headers(headers)
                .url(url)
                .post(requestBody)
                .build();
        MyOkhttpClient.getInstance().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }
            @Override
            public void onResponse(Call call, Response response){
                if(response.isSuccessful()) {
                    try {
                        String responseStr=response.body().string();
                        MyLog.writeSystemLog(responseStr);
                        sendSuccessResultCallback(responseStr, httpUtilCallBack);
                    } catch (IOException e) {
                       MyLog.writeSystemLog(e.getMessage());
                        sendFailResultCallback(response.code(),httpUtilCallBack);
                    }
                }else {
                    MyLog.writeSystemLog("response not successful  "+response.code());
                    sendFailResultCallback(response.code(),httpUtilCallBack);
                }
            }
        });
    }


    public void getReques(String url, final HttpUtilCallBack httpUtilCallBack) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = MyOkhttpClient.getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    sendSuccessResultCallback(response.body().string(), httpUtilCallBack);
                } else {
                    sendFailResultCallback(response.code(), httpUtilCallBack);
                }
            }
        });
    }

    public Call downloadFile(String url, final String filePath,final String fileName, final HttpDownloadprogressListener httpDownloadprogressListener) {
        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = MyOkhttpClient.getInstance().newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                float hasDowned = 0;
                String fileSizeStr = response.header("content-length");
                if (fileSizeStr == null) {
                    return;
                }
                float fileSize = Float.parseFloat(fileSizeStr);
                InputStream inputStream = response.body().byteStream();
                int templen = -1;
                byte[] bt = new byte[1024 * 10]; //可以根据实际情况调整，建议使用1024，即每次读1KB
                if (FileUtil.createFile(filePath, fileName)) {
                    FileOutputStream fileOutputStream = new FileOutputStream(new File(filePath+fileName));
                    while ((templen = (inputStream.read(bt))) != -1) {
                        fileOutputStream.write(bt, 0, templen); //建议不要直接用os.write(bt)
                        hasDowned = hasDowned + templen;
                        int hasDownedProgress = (int) (hasDowned / (fileSize / 100));
                        sendDownloadProgress(hasDownedProgress, fileSize, false, httpDownloadprogressListener);
                    }
                    fileOutputStream.flush();
                    inputStream.close();
                    fileOutputStream.close();
                    sendDownloadProgress(100, fileSize, true, httpDownloadprogressListener);
                }
            }
        });
        return call;
    }
    private void sendFailResultCallback(final int code, final HttpUtilCallBack callback) {
        if (callback == null) return;
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onFailure(code);
            }
        });
    }

    private void sendSuccessResultCallback(final String response, final HttpUtilCallBack callback) {
        if (callback == null) return;
        handler.post(new Runnable() {
            @Override
            public void run() {
                callback.onResponse(response);
            }
        });
    }


    private void sendDownloadProgress(final int progress, final float fileCount,final boolean isFinish,final HttpDownloadprogressListener httpDownloadprogressListener) {
        if (httpDownloadprogressListener == null) return;
        handler.post(new Runnable() {
            @Override
            public void run() {
                httpDownloadprogressListener.progress(progress,fileCount,isFinish);
            }
        });
    }


    public interface HttpUtilCallBack {
        void onFailure(int code);
        void onResponse(String responseBody);
    }

    public interface HttpDownloadprogressListener{
        void progress(int progress, float fileCount, boolean isFinish);
    }
}
